package com.kele.controller;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * @Version 2019
 * @Author:kele
 * @Date:2020/10/29
 * @Content:
 * @Description：
 */
@Controller
public class MyController {

    @RequestMapping({"/","/index"})
    public String toIndex(Model model){
        model.addAttribute("msg","welcome");
        return "index";
    }

    @RequestMapping("/add")
    public String toAdd(){
        return "add";
    }

    @RequestMapping("/update")
    public String toUpdate(){
        return "update";
    }

    @RequestMapping("/toLogin")
    public String toLogin(){
        return "login";
    }

    @RequestMapping("/login")
    public String login(String username ,String password,Model model){

        //获取当前用户
        Subject subject = SecurityUtils.getSubject();
        //封装用户的登陆数据到token
        UsernamePasswordToken token = new UsernamePasswordToken(username, password);

        //用户登录
        try {
            subject.login(token);
            return "index";
        } catch (UnknownAccountException e) {//用户名不存在
            model.addAttribute("msg","用户名错误");
            return "login";
        }catch (IncorrectCredentialsException e){//密码有问题
            model.addAttribute("msg","密码错误");
            return "login";
        }


    }

    @RequestMapping("/unauth")
    @ResponseBody
    public String toUnAuth(){
        return "未经授权，无法访问";
    }


}
